<?php
/**
 * @author AlexEllo https://github.com/AlexEllo
 * @copyright (c) 2014 AlexEllo
 * MongoDB pagination adapter for phalcon
 */
namespace Core\Paginator\Adapter;

use Phalcon\Paginator\Adapter as BaseAdapter;
use Phalcon\Paginator\Exception;
/**
 * Class Collection
 * @package Core\Paginator\Adapter
 */
class Search extends BaseAdapter
{

    /**
     * Cursor.
     *
     * @var \MongoCursor;
     */
    protected $_data;

    protected $_query;

    protected $_collection;

    protected $_skip = 5;

    /**
     * Adapter constructor.
     *
     * @param array $config Config.
     */
    public function __construct($config)
    {
        $this->_data = $config['data'];
        $this->_limit = (int)$config['limit'];
        $this->_page = (int)$config['page'];
        $this->_total = (int)$config['total'];
    }

    /**
     * Returns a slice of the resultset to show in the pagination
     *
     * @throws Exception
     * @return \stdClass
     */
    public function getPaginate()
    {
        $limit = $this->_limit;
        $pageNumber = $this->_page;
        $data = $this->_data;
        $count = $this->_total;
        $roundedTotal = $count > 0 ? ($count / intval($limit)) : 0;
        $totalPages = (int)$roundedTotal;

        /**
         * Increase total_pages if wasn't integer
         */
        if ($totalPages != $roundedTotal) {
            $totalPages++;
        }

        $pagination = paginator($totalPages, $pageNumber, $this->_skip);

        $page = new \stdClass();
        $page->pagination = $pagination;
        $page->items = $data;
        $page->next = isset($pagination[$pageNumber + 1]) ? $pageNumber + 1 : null;
        $page->first = 1;
        $page->before = isset($pagination[$pageNumber - 1]) ? $pageNumber - 1 : null;
        $page->current = $pageNumber;
        $page->last = $totalPages;
        $page->total_pages = $totalPages;
        $page->total_items = $count;
        //print_r($data);
        return $page;
    }
}